package com.xmlt.core.template.resolver;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class FilesystemResolver implements IResolver {
	private String basePath;
	private DocumentBuilder builder;

	public FilesystemResolver(String base) {
		basePath = base;
		DocumentBuilderFactory domFactory = DocumentBuilderFactory
				.newInstance();
		try {
			builder = domFactory.newDocumentBuilder();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Document find(String ref) {
		try {
			return builder.parse(basePath + ref);
		} catch (SAXException e) {
		} catch (IOException e) {
		}
		return null;
	}

	@Override
	public void save(Document doc, String ref, boolean overwrite) {
		try {
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			xformer.transform(new DOMSource(doc), new StreamResult(new File(basePath + ref)));
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<IDefaultTemplateDescriptor> getDefaultTemplateDescriptors() {
		return new ArrayList<IDefaultTemplateDescriptor>();
	}

}
